package com.zuxia.struts2.base.action;


import com.zuxia.struts2.base.entity.SendResult;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
//action 的终极父类，所有action只要继承这个类就可以不用写命名空间

//父action继承的包与命名空间
@ParentPackage(value = "pkg")
@Namespace(value = "/")
@Results(value = {
        // json 默认返回地址
        @Result(name = "json", type = "json", params = {"root", "result","callbackParameter","callback"})
    }
)
public class BaseAction implements ServletResponseAware, ServletRequestAware {
    //protected受保护的让这个对象只能被子类使用
    protected HttpServletRequest request;
    protected HttpServletResponse response;

    /*
     * 获得req，resp的对象
     * */
    @Override
    public void setServletResponse(HttpServletResponse response) {
        this.response = response;
    }

    @Override
    public void setServletRequest(HttpServletRequest request) {
        this.request = request;
    }

    /*
     *直接设置session的键值
     * */
    protected void setSessionAttribute(String key, Object value) {
        HttpSession session = request.getSession();
        session.setAttribute(key, value);
    }

    /*
     * 直接从key得到session的值，返回object
     * */
    protected Object getSessionAttribute(String key) {
        HttpSession session = request.getSession();
        return session.getAttribute(key);
    }

   /*
   * 准备一个result对象以便提交
   * 封装getset方法以便注解能识别*/
    protected SendResult result;

    public SendResult getResult() {
        return result;
    }

    public void setResult(SendResult result) {
        this.result = result;
    }
    /*
     * 拟定一个公共的数据提交方法，
     * 传入数据 填入结果为“成功”，自动封装result
     * */
    public void setSuccesResult(Object obj) {
        result = new SendResult();
        result.setSuccess(true);
        result.setData(obj);
    }

    public void setFailResult(String errorMessge){
        result = new SendResult();
        result.setSuccess(false);
        result.setErrorMessage(errorMessge);
    }

    private String callback;

    public String getCallback() {
        return callback;
    }

    public void setCallback(String callback) {
        this.callback = callback;
    }
}
